#include "InPreProcessor.h"
#include "Scuba.h"
#include<string>
#include "StringOps.h"
#include "Ark.h"
#include <iostream>

using namespace std;

InPreProcessor::InPreProcessor(Scope* pxParent)
{
    m_pxParent = pxParent;
    m_eType = Scope::eScopePreprocessor;
    m_cLookAhead = '\0';
	m_eMode = ePPInitial;
}

InPreProcessor::~InPreProcessor(void)
{
}

Scope* InPreProcessor::parse(Token& inToken, bool &bIsEndOfScope)
{
    char cDelimiter = char(inToken);
    bIsEndOfScope=false;

    switch(cDelimiter)
	{
	case '\n':
        if('\\'!=m_cLookAhead)
            bIsEndOfScope= true;
		break;

	case '<':
	case '"':
		break;
	}
    m_cLookAhead = cDelimiter;
    m_axBody.push_back(inToken);

	if(inToken.m_sValue=="include")
		m_eMode = ePPImport;
	
	if(inToken.m_sValue=="define")
		m_eMode = ePPDefine;

	if(bIsEndOfScope)
		parseBodyText();
		
    return NULL;
}

void InPreProcessor::parseBodyText()
{
	if(m_eType==ePPInitial)
		return;

	string sParseText;
	string sFilename;
	string sFullFilename;

	sParseText = getText();

	switch(m_eMode)
	{
	case ePPDefine:
		break;

	case ePPImport:
		sFilename = getContentsOf(sParseText,"\"<", "\">");
		if(sFilename!="")
		{
			sFullFilename = Ark_getAbsolutePath(sFilename);
			if(sFullFilename!="")
			{
				Scuba* pxImporter = Ark_isParsed(sFullFilename);
				if(pxImporter == NULL)
				{
					pxImporter = new Scuba(sFullFilename); //TODO: Memory Leak. Fixed with Ark?
					pxImporter->dive(sFullFilename);
				}
				m_pxParent->addRelative(pxImporter->m_pxCurrentScope);
			}
			else
			{
				cerr <<"\tCould not find " << sFilename <<endl;
			}
		}
		break;
	}
}